package com.ilxqx.framework.system.controller;

import com.google.gson.Gson;
import com.ilxqx.framework.schedule.util.ScheduleUtils;
import com.ilxqx.framework.system.config.QiNiuConfigProperties;
import com.ilxqx.framework.system.config.UploadConfigProperties;
import com.ilxqx.framework.system.upload.enumeration.FileTypeEnum;
import com.ilxqx.framework.system.upload.qiniu.service.QiNiuImgUploadService;
import com.ilxqx.framework.util.ResultUtils;
import com.ilxqx.framework.vo.ResultVO;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.Charset;

/**
 * 文件上传控制器
 * @author venus
 */
@Api("文件上传控制器")
@RestController
@RequestMapping("/sys/upload")
@Slf4j
public class UploadController {

	private final QiNiuConfigProperties qiNiuConfigProperties;
	private final Auth auth;
	private final QiNiuImgUploadService qiNiuImgUploadService;
	private final UploadConfigProperties uploadConfigProperties;

	@Autowired
	public UploadController(QiNiuConfigProperties qiNiuConfigProperties, Auth auth, QiNiuImgUploadService qiNiuImgUploadService, UploadConfigProperties uploadConfigProperties) {
		this.qiNiuConfigProperties = qiNiuConfigProperties;
		this.auth = auth;
		this.qiNiuImgUploadService = qiNiuImgUploadService;
		this.uploadConfigProperties = uploadConfigProperties;
	}

	/**
	 * 获取上传图片的凭证
	 * @return 结果对象
	 */
	@ApiOperation("获取上传图片的凭证")
	@GetMapping("/img")
	public ResultVO uploadImg() {
		return ResultUtils.success("成功", this.qiNiuImgUploadService.generateUploadToken());
	}

	/**
	 * 获取上传文件的凭证
	 * @return 结果对象
	 */
	@ApiOperation("获取上传文件的凭证")
	@GetMapping("/file")
	public ResultVO uploadFile() {
		return ResultUtils.success("成功");
	}

	@ApiOperation("上传回调通知")
	@PostMapping("/notify")
	public ResultVO uploadNotify(@RequestBody byte[] bytes,
								 @RequestHeader(value = "Authorization", required = false) String authorization) {
		// 检验请求是否合法
		if (!this.auth.isValidCallback(authorization, this.qiNiuConfigProperties.getCallbackUrl() + this.uploadConfigProperties.getImg().getCallbackPath(), bytes, MediaType.APPLICATION_JSON_VALUE)) {
			return ResultUtils.failure("这是哪里来的请求？？？");
		}
		String body = new String(bytes, Charset.forName("UTF-8"));
		Result result = new Gson().fromJson(body, Result.class);
		// 添加文件删除任务
		ScheduleUtils.startFileDeletionJob(result.getKey(), FileTypeEnum.IMAGE);
		return ResultUtils.success("上传成功", result);
	}

	@Data
	private static class Result {

		/**
		 * 文件路径和名
		 */
		private String key;

		/**
		 * 生成hash
		 */
		private String hash;

	}

}
